'use client'

import { useState, useRef, useEffect } from 'react'
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Alert, AlertDescription } from "@/components/ui/alert"
import { IconCamera, IconCheck, IconX, IconRefresh } from "@tabler/icons-react"
import { LIVENESS_BASE_URL } from '@/lib/config'

interface FaceRegisterProps {
  username: string
  onSuccess: () => void
  onCancel: () => void
}

export default function FaceRegister({ username, onSuccess, onCancel }: FaceRegisterProps) {
  const videoRef = useRef<HTMLVideoElement>(null)
  const canvasRef = useRef<HTMLCanvasElement>(null)
  const [stream, setStream] = useState<MediaStream | null>(null)
  const [capturedImages, setCapturedImages] = useState<string[]>([])
  const [isCapturing, setIsCapturing] = useState(false)
  const [isRegistering, setIsRegistering] = useState(false)
  const [error, setError] = useState('')
  const [success, setSuccess] = useState('')
  const [step, setStep] = useState<'camera' | 'capture' | 'confirm'>('camera')
  const [isVideoReady, setIsVideoReady] = useState(false)
  const [isCheckingExisting, setIsCheckingExisting] = useState(true)
  const [hasExistingFace, setHasExistingFace] = useState(false)
  const [existingFaceInfo, setExistingFaceInfo] = useState<any>(null)

  // 检查用户是否已有人脸数据
  const checkExistingFace = async () => {
    try {
      setIsCheckingExisting(true)
      setError('')
      
      const endpoint = LIVENESS_BASE_URL
      let checkUrl = endpoint
      if (checkUrl.endsWith('/')) {
        checkUrl = checkUrl.slice(0, -1)
      }
      checkUrl = `${checkUrl}/v1/face/check/${username}`
      
      console.log('检查现有人脸数据:', checkUrl)
      
      const response = await fetch(checkUrl, {
        method: 'GET'
      })
      
      if (response.ok) {
        const result = await response.json()
        if (result.success && result.has_face) {
          setHasExistingFace(true)
          setExistingFaceInfo(result)
          setSuccess(`您已经录入过人脸信息！录入时间：${new Date(result.registered_at).toLocaleString()}`)
        } else {
          setHasExistingFace(false)
          console.log('用户尚未录入人脸，可以进行新录入')
        }
      } else {
        console.log('检查人脸状态失败，假设未录入')
        setHasExistingFace(false)
      }
    } catch (error) {
      console.error('检查现有人脸数据失败:', error)
      setHasExistingFace(false)
    } finally {
      setIsCheckingExisting(false)
    }
  }

  // 重新录入人脸
  const reRegisterFace = () => {
    setHasExistingFace(false)
    setExistingFaceInfo(null)
    setSuccess('')
    setError('')
    setStep('camera')
  }

  // 删除现有人脸数据
  const deleteExistingFace = async () => {
    try {
      setIsRegistering(true)
      setError('')
      
      const endpoint = LIVENESS_BASE_URL
      let deleteUrl = endpoint
      if (deleteUrl.endsWith('/')) {
        deleteUrl = deleteUrl.slice(0, -1)
      }
      deleteUrl = `${deleteUrl}/v1/face/delete/${username}`
      
      const response = await fetch(deleteUrl, {
        method: 'DELETE'
      })
      
      if (response.ok) {
        const result = await response.json()
        if (result.success) {
          setSuccess('人脸数据已删除，可以重新录入')
          setTimeout(() => {
            reRegisterFace()
          }, 1500)
        } else {
          setError(result.message || '删除失败')
        }
      } else {
        setError('删除人脸数据失败')
      }
    } catch (error) {
      console.error('删除人脸数据失败:', error)
      setError('删除操作失败，请重试')
    } finally {
      setIsRegistering(false)
    }
  }

  // 等待视频就绪
  const waitForVideoReady = async (video: HTMLVideoElement): Promise<boolean> => {
    return new Promise((resolve) => {
      if (video.readyState >= 2 && video.videoWidth > 0) {
        resolve(true)
        return
      }

      const checkReady = () => {
        if (video.readyState >= 2 && video.videoWidth > 0) {
          resolve(true)
        }
      }

      video.addEventListener('loadeddata', checkReady)
      video.addEventListener('canplay', checkReady)
      
      // 超时保护
      setTimeout(() => {
        video.removeEventListener('loadeddata', checkReady)
        video.removeEventListener('canplay', checkReady)
        resolve(video.readyState >= 2)
      }, 5000)
    })
  }

  // 启动摄像头
  const startCamera = async () => {
    try {
      setError('')
      setIsVideoReady(false)
      
      const mediaStream = await navigator.mediaDevices.getUserMedia({ 
        video: { 
          width: 640, 
          height: 480,
          facingMode: 'user'
        } 
      })
      
      setStream(mediaStream)
      
      if (videoRef.current) {
        videoRef.current.srcObject = mediaStream
        
        // 等待视频流就绪
        const isReady = await waitForVideoReady(videoRef.current)
        setIsVideoReady(isReady)
        
        if (isReady) {
          setStep('capture')
        } else {
          setError('摄像头初始化失败，请重试')
        }
      }
    } catch (err) {
      console.error('摄像头启动失败:', err)
      setError('无法访问摄像头，请检查浏览器权限设置')
    }
  }

  // 停止摄像头
  const stopCamera = () => {
    if (stream) {
      stream.getTracks().forEach(track => track.stop())
      setStream(null)
    }
  }

  // 拍照
  const capturePhoto = () => {
    if (!videoRef.current || !canvasRef.current || capturedImages.length >= 3) return

    setIsCapturing(true)
    const video = videoRef.current
    const canvas = canvasRef.current
    const context = canvas.getContext('2d')
    
    if (!context) {
      setError('无法获取画布上下文')
      setIsCapturing(false)
      return
    }

    canvas.width = video.videoWidth
    canvas.height = video.videoHeight
    context.drawImage(video, 0, 0)
    
    const imageData = canvas.toDataURL('image/jpeg', 0.9)
    setCapturedImages(prev => [...prev, imageData])
    
    setTimeout(() => setIsCapturing(false), 300)

    // 拍摄3张照片后进入确认步骤
    if (capturedImages.length >= 2) {
      setStep('confirm')
      stopCamera()
    }
  }

  // 重新拍摄
  const retakePhotos = async () => {
    setCapturedImages([])
    setIsVideoReady(false)
    setStep('camera')
    await startCamera()
  }

  // 将 dataURL 转换为 Blob
  const dataURLToBlob = (dataUrl: string) => {
    const arr = dataUrl.split(',')
    const mime = arr[0].match(/:(.*?);/)?.[1] || 'image/jpeg'
    const bstr = atob(arr[1] || '')
    let n = bstr.length
    const u8arr = new Uint8Array(n)
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n)
    }
    return new Blob([u8arr], { type: mime })
  }

  // 提交人脸注册
  const submitRegistration = async () => {
    if (capturedImages.length === 0) {
      setError('请至少拍摄一张照片')
      return
    }

    setIsRegistering(true)
    setError('')

    try {
      // 获取API配置
      const endpoint = LIVENESS_BASE_URL
      
      // 使用第一张图片进行注册
      const imageBlob = dataURLToBlob(capturedImages[0])
      const formData = new FormData()
      formData.append('image', imageBlob, `${username}.jpg`)
      formData.append('person_name', username)
      formData.append('person_id', username)

      // 根据后端实际路由配置API路径
      let registerUrl = endpoint
      // 确保endpoint不以/结尾
      if (registerUrl.endsWith('/')) {
        registerUrl = registerUrl.slice(0, -1)
      }
      // 后端路由：app.use("/v1/face", face) + router.post("/register")
      // 完整路径：/v1/face/register
      registerUrl = `${registerUrl}/v1/face/register`
      
      console.log('正在注册人脸:', registerUrl)
      
      const response = await fetch(registerUrl, {
        method: 'POST',
        body: formData,
        // 添加超时处理
        signal: AbortSignal.timeout(30000) // 30秒超时
      })

      if (!response.ok) {
        let errorMessage = '注册失败'
        try {
          const result = await response.json()
          errorMessage = result.message || `服务器错误 (${response.status})`
        } catch {
          // 如果JSON解析失败，说明可能是HTML错误页面
          if (response.status === 404) {
            errorMessage = `API接口不存在 (404) - 请检查后端服务是否正常运行在 ${endpoint}`
          } else if (response.status >= 500) {
            errorMessage = `服务器内部错误 (${response.status}) - 请检查后端服务状态`
          } else {
            errorMessage = `注册失败 (${response.status}) - 请检查网络连接或重试`
          }
        }
        throw new Error(errorMessage)
      }

      const result = await response.json()
      
      if (result.success !== false) {
        // 保存注册状态到本地存储
        try {
          localStorage.setItem(`faceRegistered:${username}`, 'true')
          localStorage.setItem(`faceRegisteredAt:${username}`, new Date().toISOString())
        } catch {}
        
        setSuccess('人脸注册成功！现在可以使用人脸验证登录了')
        setTimeout(() => {
          onSuccess()
        }, 1500)
      } else {
        throw new Error(result.message || '注册失败，请重试')
      }
    } catch (err: any) {
      console.error('人脸注册错误:', err)
      let errorMsg = '注册失败，请检查网络连接或重试'
      
      if (err?.name === 'AbortError' || err?.name === 'TimeoutError') {
        errorMsg = '请求超时，请检查网络连接或重试'
      } else if (err?.message?.includes('Failed to fetch')) {
        errorMsg = `无法连接到服务器，请确保后端服务正在运行 (${LIVENESS_BASE_URL})`
      } else if (err?.name === 'TypeError' && err?.message?.includes('fetch')) {
        errorMsg = '网络连接失败，请检查网络或后端服务是否启动'
      } else if (err?.message) {
        errorMsg = err.message
      }
      
      setError(errorMsg)
    } finally {
      setIsRegistering(false)
    }
  }

  // 组件挂载时检查现有人脸数据
  useEffect(() => {
    checkExistingFace()
  }, [username])

  // 组件卸载时清理摄像头
  useEffect(() => {
    return () => {
      stopCamera()
    }
  }, [])

  return (
    <Card className="w-full max-w-md glass-effect border border-white/20 dark:border-gray-700/20 shadow-2xl">
      <CardHeader className="text-center pb-4">
        <div className="flex items-center justify-center gap-2 mb-2">
          <IconCamera className="w-6 h-6 text-blue-600" />
          <CardTitle className="text-lg font-semibold text-gray-900 dark:text-gray-100">
            人脸信息录入
          </CardTitle>
        </div>
        <CardDescription className="text-gray-600 dark:text-gray-400">
          {isCheckingExisting && '正在检查现有人脸数据...'}
          {!isCheckingExisting && hasExistingFace && '您已录入过人脸信息'}
          {!isCheckingExisting && !hasExistingFace && step === 'camera' && '启动摄像头开始录入'}
          {!isCheckingExisting && !hasExistingFace && step === 'capture' && `请正对摄像头，已拍摄 ${capturedImages.length}/3 张`}
          {!isCheckingExisting && !hasExistingFace && step === 'confirm' && '确认照片质量并提交注册'}
        </CardDescription>
      </CardHeader>
      
      <CardContent className="space-y-4">
        {/* 检查现有人脸数据的加载状态 */}
        {isCheckingExisting && (
          <div className="text-center py-8">
            <div className="w-8 h-8 border-2 border-blue-600 border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
            <p className="text-gray-600 dark:text-gray-400">正在检查您的人脸数据...</p>
          </div>
        )}

        {/* 已有人脸信息的处理 */}
        {!isCheckingExisting && hasExistingFace && (
          <div className="space-y-4">
            <div className="text-center p-6 bg-green-50 dark:bg-green-900/20 rounded-lg border border-green-200 dark:border-green-700/20">
              <IconCheck className="w-12 h-12 text-green-600 mx-auto mb-3" />
              <h3 className="text-lg font-semibold text-green-800 dark:text-green-400 mb-2">
                已有人脸数据
              </h3>
              <p className="text-sm text-green-700 dark:text-green-300">
                检测到您已经录入过人脸信息
              </p>
              {existingFaceInfo?.registered_at && (
                <p className="text-xs text-green-600 dark:text-green-400 mt-2">
                  录入时间：{new Date(existingFaceInfo.registered_at).toLocaleString()}
                </p>
              )}
            </div>
          </div>
        )}

        {/* 摄像头预览区域 */}
        {!isCheckingExisting && !hasExistingFace && (step === 'camera' || step === 'capture') && (
          <div className="relative bg-gray-100 dark:bg-gray-800 rounded-lg overflow-hidden">
            <video
              ref={videoRef}
              autoPlay
              playsInline
              muted
              className="w-full h-64 object-cover"
            />
            <canvas ref={canvasRef} className="hidden" />
            
            {/* 摄像头加载状态 */}
            {!isVideoReady && step === 'capture' && (
              <div className="absolute inset-0 flex items-center justify-center bg-black/50">
                <div className="text-center text-white">
                  <div className="w-8 h-8 border-2 border-white border-t-transparent rounded-full animate-spin mx-auto mb-2"></div>
                  <p className="text-sm">摄像头启动中...</p>
                </div>
              </div>
            )}
            
            {/* 拍照指示框 */}
            {step === 'capture' && isVideoReady && (
              <div className="absolute inset-0 flex items-center justify-center">
                <div className={`w-48 h-48 border-2 rounded-full transition-colors ${
                  isCapturing ? 'border-green-500' : 'border-blue-500'
                } opacity-50`}></div>
              </div>
            )}
            
            {/* 摄像头状态指示 */}
            {step === 'capture' && isVideoReady && (
              <div className="absolute top-2 right-2">
                <div className="flex items-center gap-1 bg-black/50 text-white px-2 py-1 rounded text-xs">
                  <div className="w-2 h-2 bg-green-500 rounded-full animate-pulse"></div>
                  摄像头已启动
                </div>
              </div>
            )}
            
            {/* 拍照闪光效果 */}
            {isCapturing && (
              <div className="absolute inset-0 bg-white opacity-70 animate-pulse"></div>
            )}
          </div>
        )}

        {/* 已拍摄的照片预览 */}
        {!isCheckingExisting && !hasExistingFace && capturedImages.length > 0 && (
          <div className="space-y-2">
            <h4 className="text-sm font-medium text-gray-700 dark:text-gray-300">
              已拍摄照片 ({capturedImages.length}/3)
            </h4>
            <div className="grid grid-cols-3 gap-2">
              {capturedImages.map((image, index) => (
                <img
                  key={index}
                  src={image}
                  alt={`拍摄照片 ${index + 1}`}
                  className="w-full h-20 object-cover rounded border border-gray-200 dark:border-gray-600"
                />
              ))}
            </div>
          </div>
        )}

        {/* 错误提示 */}
        {error && (
          <Alert variant="destructive" className="border-red-200 bg-red-50 dark:bg-red-900/20">
            <AlertDescription className="text-red-700 dark:text-red-300">
              {error}
            </AlertDescription>
          </Alert>
        )}

        {/* 成功提示 */}
        {success && (
          <Alert className="border-green-200 bg-green-50 dark:bg-green-900/20">
            <AlertDescription className="text-green-700 dark:text-green-300">
              {success}
            </AlertDescription>
          </Alert>
        )}

        {/* 操作按钮 */}
        <div className="flex gap-3">
          {/* 检查中的状态 */}
          {isCheckingExisting && (
            <Button disabled className="flex-1">
              <div className="flex items-center gap-2">
                <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
                检查中...
              </div>
            </Button>
          )}

          {/* 已有人脸数据时的按钮 */}
          {!isCheckingExisting && hasExistingFace && (
            <>
              <Button
                onClick={onSuccess}
                className="flex-1 bg-gradient-to-r from-green-600 to-green-700 hover:from-green-700 hover:to-green-800 text-white shadow-lg hover:shadow-xl transition-all duration-200"
              >
                <IconCheck className="w-4 h-4 mr-2" />
                确认使用
              </Button>
              <Button
                variant="outline"
                onClick={reRegisterFace}
                className="px-4"
              >
                重新录入
              </Button>
              <Button
                variant="outline"
                onClick={deleteExistingFace}
                disabled={isRegistering}
                className="px-4 text-red-600 hover:text-red-700 border-red-200 hover:border-red-300"
              >
                {isRegistering ? '删除中...' : '删除'}
              </Button>
            </>
          )}

          {/* 正常录入流程的按钮 */}
          {!isCheckingExisting && !hasExistingFace && step === 'camera' && (
            <>
              <Button
                onClick={startCamera}
                className="flex-1 bg-gradient-to-r from-blue-600 to-blue-700 hover:from-blue-700 hover:to-blue-800 text-white shadow-lg hover:shadow-xl transition-all duration-200"
              >
                <IconCamera className="w-4 h-4 mr-2" />
                启动摄像头
              </Button>
              <Button variant="outline" onClick={onCancel} className="px-4">
                取消
              </Button>
            </>
          )}

          {!isCheckingExisting && !hasExistingFace && step === 'capture' && (
            <>
              <Button
                onClick={capturePhoto}
                disabled={!isVideoReady || isCapturing || capturedImages.length >= 3}
                className="flex-1 bg-gradient-to-r from-blue-600 to-blue-700 hover:from-blue-700 hover:to-blue-800 text-white shadow-lg hover:shadow-xl transition-all duration-200 disabled:opacity-50"
              >
                {!isVideoReady ? '摄像头启动中...' : isCapturing ? '拍摄中...' : '拍照'}
              </Button>
              <Button variant="outline" onClick={onCancel} className="px-4">
                取消
              </Button>
            </>
          )}

          {!isCheckingExisting && !hasExistingFace && step === 'confirm' && (
            <>
              <Button
                onClick={submitRegistration}
                disabled={isRegistering}
                className="flex-1 bg-gradient-to-r from-blue-600 to-blue-700 hover:from-blue-700 hover:to-blue-800 text-white shadow-lg hover:shadow-xl transition-all duration-200"
              >
                {isRegistering ? (
                  <div className="flex items-center gap-2">
                    <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
                    注册中...
                  </div>
                ) : (
                  <div className="flex items-center gap-2">
                    <IconCheck className="w-4 h-4" />
                    确认注册
                  </div>
                )}
              </Button>
              <Button
                variant="outline"
                onClick={retakePhotos}
                disabled={isRegistering}
                className="px-4"
              >
                <IconRefresh className="w-4 h-4" />
              </Button>
              <Button
                variant="outline"
                onClick={onCancel}
                disabled={isRegistering}
                className="px-4"
              >
                <IconX className="w-4 h-4" />
              </Button>
            </>
          )}
        </div>

        {/* 提示信息 */}
        {!isCheckingExisting && (
          <div className="text-center">
            {hasExistingFace ? (
              <p className="text-xs text-gray-500 dark:text-gray-400">
                您可以确认使用现有人脸数据，或选择重新录入
              </p>
            ) : (
              <>
                <p className="text-xs text-gray-500 dark:text-gray-400">
                  请确保光线充足，面部清晰可见
                </p>
                {step === 'capture' && (
                  <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
                    建议从不同角度拍摄3张照片以提高识别准确率
                  </p>
                )}
              </>
            )}
          </div>
        )}
      </CardContent>
    </Card>
  )
}
